package com.gr.smartedubackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gr.smartedubackend.common.BaseResponse;
import com.gr.smartedubackend.common.DeleteRequest;
import com.gr.smartedubackend.common.ErrorCode;
import com.gr.smartedubackend.constant.UserConstant;
import com.gr.smartedubackend.model.dto.teacher.TeacherAddRequest;
import com.gr.smartedubackend.model.dto.teacher.TeacherQueryRequest;
import com.gr.smartedubackend.model.dto.teacher.TeacherUpdateRequest;
import com.gr.smartedubackend.model.entity.Teacher;
import com.gr.smartedubackend.model.entity.User;
import com.gr.smartedubackend.service.TeacherService;
import com.gr.smartedubackend.service.UserService;
import com.gr.smartedubackend.utils.ResultUtils;
import com.gr.smartedubackend.utils.ThrowUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Resource
    private TeacherService teacherService;

    @Resource
    private UserService userService;

    @PostMapping("/add")
    public BaseResponse<Long> addTeacher(@RequestBody TeacherAddRequest teacherAddRequest) {
        ThrowUtils.throwIf(teacherAddRequest == null, ErrorCode.PARAMS_ERROR);
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherAddRequest, teacher);
        boolean result = teacherService.save(teacher);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        User user = new User();
        user.setUserAccount(teacher.getTeacherNumber());
        String encryptPassword = userService.getEncryptPassword(UserConstant.DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        user.setUserName(teacher.getTeacherName());
        user.setUserAvatar(teacher.getTeacherAvatar());
        user.setUserRole(UserConstant.TEACHER_ROLE);
        result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(teacher.getId());
    }

    @GetMapping("/get")
    public BaseResponse<Teacher> getTeacherById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Teacher teacher = teacherService.getById(id);
        ThrowUtils.throwIf(teacher == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(teacher);
    }
    @GetMapping("/get/num/byGender")
    public BaseResponse<Map<String, Long>> getNumByGender() {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("gender", "COUNT(id) AS num")
                .groupBy("gender");
        List<Map<String, Object>> list = teacherService.listMaps(queryWrapper);
        Map<String, Long> result = new HashMap<>();
        for (Map<String, Object> map : list) {
            result.put(map.get("gender").toString(), (Long) map.get("num"));
        }
        return ResultUtils.success(result);
    }

    @GetMapping("/get/num/byAge")
    public BaseResponse<Map<String, Long>> getNumByAge() {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(
                "CASE " +
                        "WHEN age < 20 THEN '20以下' " +
                        "WHEN age BETWEEN 20 AND 29 THEN '20-29' " +
                        "WHEN age BETWEEN 30 AND 39 THEN '30-39' " +
                        "WHEN age BETWEEN 40 AND 49 THEN '40-49' " +
                        "ELSE '50及以上' " +
                        "END AS ageGroup",
                "COUNT(*) AS num"
        ).groupBy("ageGroup");
        List<Map<String, Object>> list = teacherService.listMaps(queryWrapper);
        Map<String, Long> result = new HashMap<>();
        result.put("20以下", 0L);
        result.put("20-29", 0L);
        result.put("30-39", 0L);
        result.put("40-49", 0L);
        result.put("50及以上", 0L);
        for (Map<String, Object> map : list) {
            result.put(map.get("ageGroup").toString(), (Long) map.get("num"));
        }
        return ResultUtils.success(result);
    }

    @PostMapping("/list/page")
    public BaseResponse<Page<Teacher>> listTeacherByPage(@RequestBody TeacherQueryRequest teacherQueryRequest) {
        ThrowUtils.throwIf(teacherQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = teacherQueryRequest.getCurrent();
        int pageSize = teacherQueryRequest.getPageSize();
        Page<Teacher> teacherPage = teacherService.page(new Page<>(current, pageSize),
                teacherService.getQueryWrapper(teacherQueryRequest));
        return ResultUtils.success(teacherPage);
    }

    @PostMapping("/list")
    public BaseResponse<List<Teacher>> listTeacher(@RequestBody TeacherQueryRequest teacherQueryRequest) {
        ThrowUtils.throwIf(teacherQueryRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(teacherService.list(teacherService.getQueryWrapper(teacherQueryRequest)));
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeacher(@RequestBody TeacherUpdateRequest teacherUpdateRequest) {
        ThrowUtils.throwIf(teacherUpdateRequest == null || teacherUpdateRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherUpdateRequest, teacher);
        boolean result = teacherService.updateById(teacher);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeacher(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        boolean result = teacherService.removeById(deleteRequest.getId());
        return ResultUtils.success(result);
    }
}
